// pages/address-edit/address-edit.js
const { addAddress, updateAddress, getAreas } = require("../../api/address.js");
const userStore = require("../../store/userStore.js");

Page({
  data: {
    isEdit: false,
    addressId: null,
    canSubmit: false,
    formData: {
      receiverName: "",
      receiverPhone: "",
      fullAddress: "",
      doorNumber: "",
      isDefault: false,
      addressTag: "",
      // 地区ID字段
      provinceId: null,
      cityId: null,
      districtId: null,
      areaId: null,
      // 地区名称字段（用于显示）
      provinceName: "",
      cityName: "",
      districtName: "",
    },
    // 地区选择相关
    showAreaPicker: false,
    currentAreaList: [],
    selectedPath: [], // 已选择的地区路径
    currentLevelText: "省份",
    // 表单验证状态
    validationErrors: {
      receiverName: "",
      receiverPhone: "",
      fullAddress: "",
      doorNumber: "",
    },
  },

  onLoad(options) {
    // 检查是否有编辑ID
    if (options.id) {
      this.setData({
        isEdit: true,
        addressId: options.id,
      });
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: "编辑收货地址",
      });
      this.loadAddressDetail(options.id);
    } else {
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: "新增收货地址",
      });
    }

    // 检查表单完整性
    this.checkFormValidity();
  },

  /**
   * 加载地址详情（编辑模式）
   */
  async loadAddressDetail(addressId) {
    try {
      wx.showLoading({ title: "加载中..." });

      // 从全局数据中获取地址数据
      const addressData = getApp().globalData.editAddressData;

      if (addressData) {
        // 构建表单数据
        const formData = {
          receiverName: addressData.receiverName || "",
          receiverPhone: addressData.receiverPhone || "",
          fullAddress: addressData.fullAddress || "",
          doorNumber: addressData.receiverAddress || "", // 门牌号对应receiverAddress字段
          isDefault: addressData.isDefault || false,
          addressTag: addressData.addressTag || "",
          // 地区ID字段
          provinceId: addressData.provinceId || null,
          cityId: addressData.cityId || null,
          districtId: addressData.districtId || null,
          areaId: addressData.areaId || null,
          // 地区名称字段（用于显示）
          provinceName: addressData.provinceName || "",
          cityName: addressData.cityName || "",
          districtName: addressData.districtName || "",
        };

        this.setData({
          formData: formData,
        });

        // 清除全局数据
        delete getApp().globalData.editAddressData;
      } else {
        // 如果没有传递数据，显示错误
        wx.showToast({
          title: "地址数据加载失败",
          icon: "none",
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }

      wx.hideLoading();
      this.checkFormValidity();
    } catch (error) {
      wx.hideLoading();
      console.error("加载地址详情失败:", error);
      wx.showToast({
        title: "加载失败，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 收货人姓名输入
   */
  onReceiverNameInput(e) {
    this.setData({
      "formData.receiverName": e.detail.value,
    });
    this.checkFormValidity();
  },

  /**
   * 手机号输入
   */
  onPhoneInput(e) {
    this.setData({
      "formData.receiverPhone": e.detail.value,
    });
    this.checkFormValidity();
  },

  /**
   * 门牌号输入
   */
  onDoorNumberInput(e) {
    this.setData({
      "formData.doorNumber": e.detail.value,
    });
    this.checkFormValidity();
  },

  /**
   * 选择地址
   */
  chooseAddress() {
    // 打开地区选择抽屉
    this.openAreaPicker();
  },

  /**
   * 打开地区选择抽屉
   */
  async openAreaPicker() {
    try {
      wx.showLoading({ title: "加载中..." });

      // 加载省份列表
      const response = await getAreas({
        areaLevel: "1",
        parentId: "",
      });

      wx.hideLoading();

      if (response.code === 0) {
        this.setData({
          showAreaPicker: true,
          currentAreaList: response.data || [],
          selectedPath: [],
          currentLevelText: "省份",
        });
      } else {
        wx.showToast({
          title: response.message || "加载失败",
          icon: "none",
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error("加载省份列表失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 关闭地区选择抽屉
   */
  closeAreaPicker() {
    this.setData({
      showAreaPicker: false,
      currentAreaList: [],
      selectedPath: [],
    });
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {
    // 阻止事件冒泡，防止点击抽屉内容时关闭抽屉
  },

  /**
   * 选择地区
   */
  async selectArea(e) {
    const area = e.currentTarget.dataset.area;

    // 添加到选择路径
    const newPath = [...this.data.selectedPath, area];

    if (area.areaLevel === "3") {
      // 选择了区县，完成选择
      this.completeAreaSelection(newPath);
    } else {
      // 选择了省或市，继续加载下一级
      try {
        wx.showLoading({ title: "加载中..." });

        const nextLevel = parseInt(area.areaLevel) + 1;
        const response = await getAreas({
          areaLevel: nextLevel.toString(),
          parentId: area.id.toString(),
        });

        wx.hideLoading();

        if (response.code === 0) {
          const levelText = nextLevel === 2 ? "城市" : "区县";
          this.setData({
            currentAreaList: response.data || [],
            selectedPath: newPath,
            currentLevelText: levelText,
          });
        } else {
          wx.showToast({
            title: response.message || "加载失败",
            icon: "none",
          });
        }
      } catch (error) {
        wx.hideLoading();
        console.error("加载下级地区失败:", error);
        wx.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      }
    }
  },

  /**
   * 完成地区选择
   */
  completeAreaSelection(path) {
    // 构建完整地址显示
    const fullAddress = path.map((item) => item.areaName).join("");

    // 提取各级地区信息
    const province = path.find((item) => item.areaLevel === "1");
    const city = path.find((item) => item.areaLevel === "2");
    const district = path.find((item) => item.areaLevel === "3");

    this.setData({
      "formData.fullAddress": fullAddress,
      "formData.provinceId": province ? province.id : null,
      "formData.cityId": city ? city.id : null,
      "formData.districtId": district ? district.id : null,
      "formData.areaId": district ? district.id : null, // areaId使用区县ID
      "formData.provinceName": province ? province.areaName : "",
      "formData.cityName": city ? city.areaName : "",
      "formData.districtName": district ? district.areaName : "",
      showAreaPicker: false,
      currentAreaList: [],
      selectedPath: [],
    });

    this.checkFormValidity();

    wx.showToast({
      title: "地址选择完成",
      icon: "success",
    });
  },

  /**
   * 返回上级地区
   */
  async goBackToLevel(e) {
    const level = e.currentTarget.dataset.level;
    const newPath = this.data.selectedPath.slice(0, level + 1);

    if (level === 0) {
      // 返回省份列表
      try {
        wx.showLoading({ title: "加载中..." });

        const response = await getAreas({
          areaLevel: "1",
          parentId: "",
        });

        wx.hideLoading();

        if (response.code === 0) {
          this.setData({
            currentAreaList: response.data || [],
            selectedPath: [],
            currentLevelText: "省份",
          });
        }
      } catch (error) {
        wx.hideLoading();
        console.error("加载省份列表失败:", error);
      }
    } else {
      // 返回上级地区列表
      const parentArea = newPath[newPath.length - 1];
      const nextLevel = parseInt(parentArea.areaLevel) + 1;

      try {
        wx.showLoading({ title: "加载中..." });

        const response = await getAreas({
          areaLevel: nextLevel.toString(),
          parentId: parentArea.id.toString(),
        });

        wx.hideLoading();

        if (response.code === 0) {
          const levelText = nextLevel === 2 ? "城市" : "区县";
          this.setData({
            currentAreaList: response.data || [],
            selectedPath: newPath,
            currentLevelText: levelText,
          });
        }
      } catch (error) {
        wx.hideLoading();
        console.error("加载地区列表失败:", error);
      }
    }
  },

  /**
   * 打开地址粘贴板
   */
  openClipboard() {
    wx.showToast({
      title: "地址粘贴板功能开发中",
      icon: "none",
    });
  },

  /**
   * 默认地址开关
   */
  onDefaultChange(e) {
    this.setData({
      "formData.isDefault": e.detail.value,
    });
  },

  /**
   * 选择标签
   */
  selectTag(e) {
    const tag = e.currentTarget.dataset.tag;
    this.setData({
      "formData.addressTag": tag,
    });
  },

  /**
   * 检查表单完整性
   */
  checkFormValidity() {
    const {
      receiverName,
      receiverPhone,
      fullAddress,
      doorNumber,
      provinceId,
      cityId,
      districtId,
    } = this.data.formData;

    // 验证错误信息
    const errors = {
      receiverName: "",
      receiverPhone: "",
      fullAddress: "",
      doorNumber: "",
    };

    // 收货人姓名验证
    if (!receiverName.trim()) {
      errors.receiverName = "收货人姓名不能为空";
    } else if (receiverName.length > 20) {
      errors.receiverName = "收货人姓名长度不能超过20个字符";
    }

    // 手机号验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!receiverPhone.trim()) {
      errors.receiverPhone = "收货人电话不能为空";
    } else if (!phoneRegex.test(receiverPhone)) {
      errors.receiverPhone = "手机号格式不正确";
    }

    // 地址验证
    if (!fullAddress.trim()) {
      errors.fullAddress = "请选择收货地址";
    }

    // 门牌号验证
    if (!doorNumber.trim()) {
      errors.doorNumber = "详细地址不能为空";
    } else if (doorNumber.length > 255) {
      errors.doorNumber = "详细地址长度不能超过255个字符";
    }

    // 地区选择验证
    if (!provinceId || !cityId || !districtId) {
      errors.fullAddress = "请完整选择省市区";
    }

    const isValid = Object.values(errors).every((error) => error === "");

    this.setData({
      canSubmit: isValid,
      validationErrors: errors,
    });
  },

  /**
   * 提交地址
   */
  async submitAddress() {
    if (!this.data.canSubmit) {
      wx.showToast({
        title: "请完善必填信息",
        icon: "none",
      });
      return;
    }

    try {
      wx.showLoading({ title: this.data.isEdit ? "更新中..." : "保存中..." });

      const submitData = {
        receiverName: this.data.formData.receiverName,
        receiverPhone: this.data.formData.receiverPhone,
        provinceId: this.data.formData.provinceId,
        cityId: this.data.formData.cityId,
        districtId: this.data.formData.districtId,
        receiverAddress: this.data.formData.doorNumber,
        areaId: this.data.formData.areaId,
        isDefault: this.data.formData.isDefault,
        addressTag: this.data.formData.addressTag || "",
      };

      let response;
      if (this.data.isEdit) {
        response = await updateAddress({
          id: this.data.addressId,
          ...submitData,
        });
      } else {
        response = await addAddress(submitData);
      }

      wx.hideLoading();

      if (response.code === 0) {
        wx.showToast({
          title: this.data.isEdit ? "更新成功" : "保存成功",
          icon: "success",
        });

        // 如果是新增地址，将新地址信息存储到全局数据中
        if (!this.data.isEdit) {
          const newAddress = {
            id: response.data?.id || Date.now().toString(), // 使用返回的ID或临时ID
            receiverName: this.data.formData.receiverName,
            receiverPhone: this.data.formData.receiverPhone,
            receiverProvince: this.data.formData.provinceName,
            receiverCity: this.data.formData.cityName,
            receiverDistrict: this.data.formData.districtName,
            receiverAddress: this.data.formData.doorNumber,
            postalCode: null,
            isDefault: this.data.formData.isDefault || false,
            addressTag: this.data.formData.addressTag || "",
            fullAddress: `${this.data.formData.provinceName}${this.data.formData.cityName}${this.data.formData.districtName}${this.data.formData.doorNumber}`,
            status: 1, // 新添加的地址默认为有效
          };

          // 存储到全局数据中
          getApp().globalData.newAddress = newAddress;
        }

        // 延迟返回，让用户看到成功提示
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        // 显示后端返回的具体错误信息
        wx.showModal({
          title: "保存失败",
          content: response.message || "操作失败，请重试",
          showCancel: false,
          confirmText: "确定",
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error("提交地址失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    }
  },
});
